/* util */
const { isRegExp } = require('lodash')
/* plugins */
const { ESBuildMinifyPlugin } = require('esbuild-loader')

function replaceToEsBuild(config) {
  const module = config ? config.module || {} : {}
  // 规则
  let rules = module.rules
  // 正则
  let test
  
  rules = rules.filter(rule => {
    test = rule.test
    if (!isRegExp(test)) return true
    
    return !test.test('.tsx') && !test.test('.js')
  })
  
  rules = rules.concat([
    {
      test: /\.js$/,
      loader: 'esbuild-loader',
      options: {
        // 没有使用jsx可以改成js
        loader: 'jsx',
        target: 'es2015'
      }
    },
    {
      test: /\.tsx?$/,
      loader: 'esbuild-loader',
      options: {
        // 没有使用tsx可以改成ts
        loader: 'tsx',
        target: 'es2015'
      }
    }
  ])
  
  if (config && config.module) {
    config.module.rules = rules
  }
  
  if (config && config.optimization) {
    const originMinimizer = config.optimization.minimizer || []
    config.optimization.minimizer = originMinimizer.concat([
      new ESBuildMinifyPlugin({
        target: 'es2015',
        css: true
      })
    ])
  }
  
}

module.exports = replaceToEsBuild
